﻿using RepositoryAndEf.Domain;
using RepositoryAndEf.Core.Data;
using System.Collections.Generic;
using RepositoryAndEf.Core.Common;
using RepositoryAndEf.Data;
using System;

namespace RepositoryAndEf.Service
{
    public class ShoppingCartService : IShoppingCartService
    {
        private IRepository<ShoppingCart> _shoppingCartRepository;
        private IRepository<Product> _productRepository;

        public ShoppingCartService(IRepository<ShoppingCart> shoppingCartRepository,
            IRepository<Product> productRepository)
        {
            _shoppingCartRepository = shoppingCartRepository;
            _productRepository = productRepository;
        }

        public ShoppingCart AddToCart(Guid cartId, Guid productId, int quantity)
        {
            var cart = _shoppingCartRepository.GetById(cartId);
            var product = _productRepository.GetById(productId);
            cart.AddItem(product, quantity);

            _shoppingCartRepository.Update(cart);
            return cart;
        }

        public ShoppingCart UpdateCartItemQuantity(Guid cartId, Guid productId, int newQuantity)
        {
            var cart = _shoppingCartRepository.GetById(cartId);
            cart.ChangeProductQuantity(productId, newQuantity);

            return cart;
        }

        public ShoppingCart RemoveCartItem(Guid cartId, IEnumerable<Guid> productIds)
        {
            var cart = _shoppingCartRepository.GetById(cartId);
            foreach (var productId in productIds)
            {
                cart.RemoveItem(productId);
            }

            return cart;
        }
    }

}
